package prepare

import (
	"fmt"

	"cke.io/ckectl/app/cmd/options"
	common "cke.io/ckectl/app/cmd/phases"
	"github.com/pkg/errors"
	kubeoptions "k8s.io/kubernetes/cmd/kubeadm/app/cmd/options"
	"k8s.io/kubernetes/cmd/kubeadm/app/cmd/phases/workflow"
	cmdutil "k8s.io/kubernetes/cmd/kubeadm/app/cmd/util"
)

var (
	dockerPhaseExample = cmdutil.Examples(`
		# Writes a dynamic environment file with kubelet flags from a InitConfiguration file.
		kubeadm init phase kubelet-start --config config.yaml
		`)
)

// NewKubeletStartPhase creates a kubeadm workflow phase that start kubelet on a node.
func NewDockerPhase() workflow.Phase {
	return workflow.Phase{
		Name:    "docker",
		Short:   "Write kubelet settings and (re)start the kubelet",
		Long:    "Write a file with KubeletConfiguration and an environment file with node specific kubelet settings, and then (re)start kubelet.",
		Example: dockerPhaseExample,
		Run:     runDocker,
		InheritFlags: []string{
			options.LocalHostName,
			options.InsecureRegistry,
			options.DockerPreconfiged,
			options.AnsibleImageName,
			options.AllKnowDomains,
			kubeoptions.CfgPath,
		},
	}
}

// runKubeletStart executes kubelet start logic.
func runDocker(c workflow.RunData) error {
	data, err := common.GetInitConfiguration(c)
	if err!=nil {
		return errors.New("can't get Init Configuration: " + err.Error())
	}

	err = common.AddKnowDomains(data.Ansible.Domains...)
	// write incert registry
	if !common.SliceContains(data.Ansible.DockerPreconfiged, data.Ansible.LocalHostName) {
		err = common.WriterIncertRegistry(data.InsecureRegistry)
		if err != nil {
			fmt.Println("Waring: fail to restart docker")
		}
		defer common.DockerRestart()
	}

	return common.CommonPhase("prepare", "docker").Run(c)
}
